package cn.it.shop.util;

import java.util.Collection;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

@Service("accessDecisionManager")
public class ShopAccessDecisionManager implements AccessDecisionManager {
	
	/*
	 *  吧用户的角色信息与资源的角色信息都作为参数传递到此方法中
	 *  如果方法执行完毕没有抛出异常则说明认证成功, 否则认证失败
	 * */

	@Override
	public void decide(Authentication authentication, Object object,
			Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
		System.out.println("-----------decide() 当前:getAttributes 通过URL地址查询返回角色集合时候,调用此方法, 完成权限的判断----------------------");
		for(GrantedAuthority userRole:authentication.getAuthorities()){
			for(ConfigAttribute urlRole:configAttributes){
				if(userRole.getAuthority().equals(urlRole.getAttribute())){
					return;
				}
			}
		}
		throw new AccessDeniedException("访问拒绝!"); 
	}

	@Override
	public boolean supports(ConfigAttribute attribute) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		// TODO Auto-generated method stub
		return true;
	}

}
